import { Component, OnInit } from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { Router, ActivatedRoute } from "@angular/router";
import { HttpServcie } from "../../../../service/http.service";
import { Config } from "../../../../service/config";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
import { PlanDetailBean } from "../plan-detail.bean";
import {ElevatorInfoBean} from "../../../elevator/elevator-info/bean/elevatorInfo.bean";
import {DetectionRecordBean} from "../../../detection/detection-record.bean";

@Component({
  selector: "plan-detail",
  templateUrl: "plan-detail.html",
  styleUrls: ["plan-detail.scss"]
})
export class PlanDetail implements OnInit {
  modelTitle: string;
  modal: number;
  updateData: any;
  planDetail: PlanDetailBean = new PlanDetailBean();
  list: any = [];
  allChecked = false;
  indeterminate = false;
  currentModal: any;
  isConfirmLoading = false;
  isAddVisible = false;
  checkStateList = Config.checkStateList;
  config = Config;
  total = 0;
  inDictData: any;
  planDict: any = {};
  elevatorInfo :　ElevatorInfoBean = new ElevatorInfoBean();
  elevatorTypes : any = [
    {'label' : '载客电梯', 'value' : '1'},
    {'label' : '载货电梯', 'value' : '5'},
    {'label' : '自动扶梯', 'value' : '4'},
    {'label' : '自动人行道', 'value' : '6'},
    {'label' : '液压驱动电梯', 'value' : '2'},
    {'label' : '杂物电梯', 'value' : '3'}];  //按需维保申请状态

  //获取电梯参数
  showFlag : boolean = false;
  elevatorList : any = [];
  elevatorNumList = [];
  elevatorTotal = 0;

  //查询电梯台账条件
  elevatorAgeParam : any;
  elevatorNum : string;
  elevatorTypeParam : any;

  tempPlanDetail : any;
  pageSize:number = 10;
  currentPage:number = 1;
  eleAllChecked = false;
  eleIndeterminate = false;
  elevatorIds : string;

  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
    this.activatedRoute.params.subscribe(data => {
      //深度 clone 一下，否则不能修改
      this.planDict = Object.assign({}, data);
      this.planDetail.planDictId = this.planDict.id;
      if(this.planDict.pdType == '5'){
        this.showFlag = true;
      }
    });
    this.planDetail.currentPage = 1;
    this.planDetail.pageSize = 10;
    // this.query();
  }

  ngOnInit() {
  }

  query() {
    this.httpServcie.queryPlanDetail(this.planDetail).subscribe(data => {
      if (data.status == 200) {
        this.list = data.data.list;
        this.total = data.data.total;
      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else {
        this._notification.create("error", "失败", "查询出错！请重试");
      }
    });
  }

  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  //table加载数据时
  displayDataChange($event,type) {
    if(type == '1'){
      this.elevatorList = $event;
    }else{
      this.list = $event;
    }
    this.refreshStatus($event,type);
  }

  //重置选择框
  refreshStatus($event,type) {
    let tempList: any = [];
    if(type == '1'){
      tempList = this.elevatorList;
    }else{
      tempList = this.list;
    }
    const allChecked = tempList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = tempList.every(
      value => value.disabled || !value.checked
    );
    if(type == '1'){
      this.eleAllChecked = allChecked;
      this.eleIndeterminate = !allChecked && !allUnChecked;
    }else{
      this.allChecked = allChecked;
      this.indeterminate = !allChecked && !allUnChecked;
    }
  }

  //全选
  checkAll(value,type) {
    let tempList: any = [];
    if(type == '1'){
      tempList = this.elevatorList;
    }else{
      tempList = this.list;
    }
    if (value) {
      tempList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      tempList.forEach(data => (data.checked = false));
    }
  }

  /**
   * 委托检测获取电梯
   */
  queryElevator(data){
    let param : any = {
      "elevatorAgeParam" : "",
      "elevatorTypeParam" : "",
      "usedPartyId" : "",
      "maintenancePartyId" : "",
      "elevatorNum" : "",
      "pageSize" : this.pageSize,
      "currentPage" : this.currentPage,
    };
    if(this.elevatorTypeParam !=null && this.elevatorTypeParam !=""){
      param.elevatorTypeParam = this.elevatorTypeParam.join(",");
    }
    if(this.elevatorAgeParam !=null && this.elevatorAgeParam !=""){
      param.elevatorAgeParam = this.elevatorAgeParam.join(",");
    }
    if(this.elevatorNum !=null && this.elevatorNum !=""){
      param.elevatorNum = this.elevatorNum;
    }
    if(data.be_party_type == '使用单位'){
      param.usedPartyId = data.be_cked_party_id;
    }
    if(data.be_party_type == '维保单位'){
      param.maintenancePartyId = data.be_cked_party_id;
    }

    this.httpServcie.detectionGetElevator(param).subscribe(data => {
        if (data.status === 200) {
          console.log(data);
          this.elevatorList = data.data.list;
          this.elevatorTotal = data.data.total;
          if(this.elevatorNumList.length > 0){
            this.elevatorList.forEach(ele1 =>{
              this.elevatorNumList.forEach(ele2 =>{
                if(ele1.num == ele2){
                  ele1.checked = true;
                }
              });
            });
          }

        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 保存勾选的电梯
   */
  saveElevators(){

    //再次点击时重新给值
    let isNo = false;
    const tempList: any = [];
    this.elevatorList.forEach(element => {
      let isNotExist = true;
      if (element.checked) {
        if(!isNo){
          tempList.push(element);
          this.elevatorNumList.forEach(element1 =>{
            if(element.id == element1){
              isNotExist = false;
            }
          });
          if(isNotExist){
            this.elevatorNumList.push(element.elevatorNum + "");
          }
        }
      }
    });
    if (tempList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "至少选中一条数据！");
      return;
    }
  }

  /**
   * 清除已选择的电梯数据
   */
  clear(){
    this.elevatorList.forEach(ele1 =>{
      this.elevatorNumList.forEach(ele2 =>{
        if(ele1.num == ele2){
          ele1.checked = false;
        }
      });
    });
    this.elevatorNumList.splice(0,this.elevatorNumList.length);
  }

  /**
   * 提交已选择的电梯数据
   */
  submit(){
    if(this.elevatorNumList.length == 0){
      this._notification.create("warning", "警告提示", "请勾选电梯信息，保存后提交！");
      return;
    }
    let detectionElevators : any = [];
    this.elevatorNumList.forEach(ele =>{
      let detectionElevator : DetectionRecordBean = new DetectionRecordBean();
      detectionElevator.elevatorNum = ele;
      detectionElevator.planDetailId = this.tempPlanDetail.id;
      detectionElevator.isPass = '0';
      detectionElevators.push(detectionElevator);
    });
    this.httpServcie.addDetectionElevator(detectionElevators).subscribe(data =>{
      if(data.status == '200'){
        this._notification.create("success", "成功提示", "配置电梯成功");
        return;
      }
    });
    this.currentModal.destroy();
  }

  //分页
  nzPageSizeChange($event,type) {
    if(type == '1'){
      this.currentPage = 1;
      this.pageSize = $event;
      this.queryElevator(this.tempPlanDetail);
    }else{
      this.planDetail.pageSize = $event;
      this.planDetail.currentPage = 1;
      this.query();
    }
  }

  //输入框的方法
  nzPageIndexChange($event,type) {
    if(type == '1'){
      this.currentPage = $event;
      this.queryElevator(this.tempPlanDetail);
    }else{
      this.planDetail.currentPage = $event;
      this.query();
    }
  }

  //当前页
  nzPageIndexClickChange($event,type) {
    if(type == '1'){
      this.currentPage = $event;
      // this.queryElevator(this.tempPlanDetail);
    }else{
      this.currentPage = $event;
      // this.query();
    }
  }

  //添加
  // this.isAddVisible = true;
  add(titleTpl, contentTpl, footerTpl, checkType) {
    this.modelTitle = "添加";
    this.modal = 0;

    const updateList: any = [];
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = Object.assign({}, element);
      }
    });
    this.updateData["checkType"] =  checkType;
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    if(this.updateData.pd_type == '5' && checkType == '2' ){
      this._notification.create("warning", "警告提示", "委托检测任务，只能向单位下达！");
      return;
    }
    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  addElevator(title,content,footer,data){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("error", "错误提示", "您无权限");
      return;
    }
    this.pageSize = 10;
    this.currentPage = 1;
    this.modelTitle = "添加电梯";
    this.modal = 3;
    this.tempPlanDetail = data;
    this.queryElevator(data);
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 1000,
      zIndex: 2000,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  /**
   * 查看委托检测添加的电梯
   */
  checkElevator(param){
    this.router.navigate(['/home/detection-record',{planDetailId:param}]);
  }

  delete() {
    const updateList: any = [];
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = Object.assign({}, element);
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    let thiss = this;
    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpServcie.deletePlanDetail({
          id: thiss.updateData.id
        });
        ob.subscribe(
          data => {
            if (data.status == 200) {
              thiss._notification.create("success", "成功", "删除成功");
              thiss.planDetail.currentPage = 1;
              thiss.query();
            } else if (data.status == 401) {
              thiss._notification.create("error", "失败", "请重新登录");
              thiss.router.navigateByUrl("/login");
            } else {
              thiss._notification.create("error", "失败", "查询出错！请重试");
            }
          },
          error => {
            thiss._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() {}
    });
  }
  //修改
  update(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "修改";
    this.modal = 1;
    const updateList: any = [];

    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = Object.assign({}, element);
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 600,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //添加添加页面的数据
  handleOk(e) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 1000);
    // this.isAddConfirmLoading = true;
    // this.inValue = "aaaaa";
  }

  //关闭model框
  handleCancel = e => {
    console.log(e);
    this.isAddVisible = false;
  };

  //添加后返回的结果
  addOutPut(event) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
    this.planDetail.currentPage = 1;
    this.query();
  }

  //导入计划明细
  importPlanD(title, content, footer, data) {
    this.inDictData = Object.assign({}, data);
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 500,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //上传回调
  uploadChage(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "导入成功");
        this.currentModal.destroy();
      }
    }
  }

  toBack() {
    window.history.back();
  }
}
